/**

 @Name：公共方法
 @Author：lixin
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */
 
layui.define(function(exports){
    var layer = layui.layer,
        Tools = {};
    
    /**
     * 获取容器内的值
     * @param  {object} $container 容器的jQuery对象
     * @param  {object} subFun     fun 用于修改容器内的值/{string}：用于过滤数据, isArray 
     */
    Tools.getAreaArgs = function($container, subFun, checkFun) {
        subFun = subFun || {};
        var res = [], $fields, name, value, $field,
            val,
            hasSubFun = typeof subFun.fun === 'function';

        $container.each(function(index, el) {
            var obj = {};
            $fields = $(this).find("input, select,textarea");

            if (typeof checkFun === 'function') {
                if (!checkFun($(this))) return true;
            }
            if ($fields.length) {
                $fields.each(function(index, el) {
                    $field = $(this);

                    if (!!$field.attr('name')) {
                        val = $.trim($field.val());
                        if (this.tagName.toLowerCase() === 'input') {
                            if ($field.closest('label').hasClass('hidden')) return;
                            switch(this.type) {
                                case 'radio':
                                    if (!this.checked) return true;
                                break;
                                case 'checkbox':
                                    if (!!subFun && subFun.input == 1) {
                                        val = this.checked ? 1 : 0;
                                    } else {
                                        val = this.checked;
                                    }
                                break;
                                default: break;
                            }
                        }
                        obj[$field.attr('name')] = val;
                    }
                });

                if (hasSubFun) {
                    obj = $.extend(true, obj, subFun.fun($(this)));
                }

                if (!$.isEmptyObject(obj)) {
                    res.push(obj);
                }
            }
        });

        if (!!subFun) {
            switch(subFun.type) {
                case 'array':
                break;
                default:
                    if (res.length > 0) {
                        var json = {};
                        for (var i = res.length - 1; i >= 0; i--) {
                            $.extend(json, res[i]);
                        }
                        return json;
                    } else {
                        return {};
                    }
                break;
            }
        }
        return res;
    };

    /**
    * 销毁iframe，释放iframe所占用的内存。
    * @param iframe 须要销毁的iframe对象
    */
	Tools.destroyIframe = function(iframe){
        //把iframe指向空白页面，这样能够释放大部分内存。
        iframe.src = 'about:blank';
        try{
            iframe.contentWindow.document.write('');
            iframe.contentWindow.document.clear();
        }catch(e){}
        //把iframe从页面移除
        iframe.parentNode.removeChild(iframe);
    };

     /**
     * 下载文件方法 兼容IE8
     * @param {*} url 
     * @param {*} args 
     */
    Tools.downLoadfunction = function(url, args,errortxt) { 
     	 $.fileDownload(url,{
  	        httpMethod: 'post',
  	        dataType: "json", 
  	        data:args||{},
  	        enctype: "application/x-www-form-urlencoded;charset=utf-8",
  	        prepareCallback:function(url){
  	        	 
  	        },
  	        failCallback: function (html, url){
                layui.use("layer",function(){
                    var layer=layui.layer; 
                    if(errortxt){
                        layer.msg("无文件下载！",{time: 1000});
                    }else{ 
                        layer.msg( "导出失败！",{time: 1000});
                    }
                }) 
  	        }
  	     })
    } 
    //判断是否为空
    //判断对象是否为空
    Tools.isEmpty=function(strParam){
        for(var key in strParam){
        var obj=strParam[key];
        var emptyF=true; 
            if(typeof obj == "undefined" || obj == null || obj == ""){
                    emptyF=true;
                }else{
                    return false
                }
            }  
        return emptyF
    }
    //多文件下载 
    Tools.downLoadMutipleFileFun = function(taskid) { 
     	 $.fileDownload('myapi/DC/api/rest/web/custom/fileDownloadByServername',{
  	        httpMethod: 'post',
  	        dataType: "json", 
  	        data:{
                taskid:taskid,
                access_token:layui.data('layuiAdmin').access_token
              }, 
              enctype: "application/x-www-form-urlencoded;charset=utf-8",
            contentType:'multipart/form-data',
  	        prepareCallback:function(url){
  	        	 
  	        },
  	        failCallback: function (html, url){ 
                    var htmlObj=JSON.parse(html);
                    if(htmlObj||htmlObj.retcode=="-1"){ 
                        var textP=htmlObj.retmsg||'文件不存在'
                        layui.use("layer",function(){
                            var layer=layui.layer; 
                            layer.msg(textP,{time: 1000});
                        }) 
                    } 
  	        }
  	     })
    } 
    //数据审核多文件下载
    Tools.downLoadMutipleDataFun = function(url,downloadParam) { 
        $.fileDownload(url,{
            httpMethod: 'post',
            dataType: "json", 
            data:downloadParam||{},
            // data:{
            //   taskid:taskid,
            //   access_token:layui.data('layuiAdmin').access_token
            // }, 
            enctype: "application/x-www-form-urlencoded;charset=utf-8",
          contentType:'multipart/form-data',
            prepareCallback:function(url){
                 
            },
            failCallback: function (html, url){    
                  var htmlObj=JSON.parse(html);
                  if(htmlObj||htmlObj.retcode=="-1"){ 
                      var textP=htmlObj.retmsg||'文件不存在'
                      layui.use("layer",function(){
                          var layer=layui.layer; 
                          layer.msg(textP,{time: 1000});
                      }) 
                  } 
            }
         })
  } 
    /**
     * 下载文件方法 兼容IE8  抛弃此方法
     * @param {*} url 
     * @param {*} name 
     */
    Tools.downMethodfunction = function(url, name,taskid,downloadFlag) {  
        var newSernerNameArr=url.split("/");  
        if (!!window.ActiveXObject || "ActiveXObject" in window) { 
            var downLoadUrl='myapi/DC/api/rest/web/custom/fileDownloadByServername';
            var downloadParam={
                servername:newSernerNameArr[newSernerNameArr.length-1], 
                taskid:taskid||"",
                access_token:layui.data('layuiAdmin').access_token
            }
            if(downloadFlag=="export"){
                downLoadUrl='myapi/DC/api/rest/web/custom/fileDownloadByName';
                downloadParam={
                    fileName:newSernerNameArr[newSernerNameArr.length-1],
                    name:name,
                    access_token:layui.data('layuiAdmin').access_token
                }
            }
            $.fileDownload(downLoadUrl,{
                httpMethod: 'post',
                dataType: "json", 
                enctype: "application/x-www-form-urlencoded;charset=utf-8",
                contentType:'multipart/form-data',
                data:downloadParam,
                prepareCallback:function(url,kkk){ 

                },
                successCallback:function(url,mmmm){ 

                },
                failCallback: function (html, url){  
                    var htmlObj=JSON.parse(html);
                    if(htmlObj||htmlObj.retcode=="-1"){ 
                        var textP=htmlObj.retmsg||'文件不存在'
                        layui.use("layer",function(){
                            var layer=layui.layer; 
                            layer.msg(textP,{time: 1000});
                        }) 
                    } 
	        	 
                }
            })

            //ie
            // 拼接随机字符url,防止页面缓存
            // var randomName = name + "?time="+new Date().getTime();
            // var randomUrl = url + "?time="+new Date().getTime(); 
            // var oPow = window.open(randomUrl, randomName, "width = 1, height = 1, top = 5000, left = 5000"); 
            // var isOpen = true; //判断window.open是否被禁用
            // try {
            //     if (oPow == null) {
            //         isOpen = false
            //     };
            // } catch (err) {
            //     isOpen = false
            // };
            // if (!!isOpen) {
            //     //没禁用window.open采用window.open下载
            //     while (oPow.document.readyState !== "compvare") {
            //         if (oPow.document.readyState === "compvare") break;
            //     }
            //     oPow.document.execCommand("SaveAs", true, name);
            //     oPow.close();
            // }else {
            //     //禁用了window.open采用iframe下载
            //     var oIrame = document.createElement('iframe');
            //     oIrame.style.width = "0px";
            //     oIrame.style.height = "0px";
            //     oIrame.style.opacity = 1;
            //     document.body.appendChild(oIrame);
            //     oIrame.src = randomUrl;
            //     var IfDoc = oIrame.contentDocument || oIrame.document;
            //     oIrame.onreadystatechange = function () { // IE下的节点都有onreadystatechange这个事件  
            //         if (oIrame.readyState == "compvare") {
            //             // oIrame.execCommand("SaveAs", true, name)
            //             document.body.removeChild(oIrame);
            //         };
            //     };
            //  };
        } else {
            if (typeof url == 'object' && url instanceof Blob) {
                url = URL.createObjectURL(url); // 创建blob地址
            };
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = name || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if (window.MouseEvent) {
                event = new MouseEvent('click');
            } else {
                if (document.createEvent) {
                    event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                };
            };
            aLink.dispatchEvent(event);
        };
    };

    /** 
     * 数组对象去重
     */
    Tools.uniqueArr = function(arr, id) {
        var res = [];
        var json = {};
        for(var i = 0; i < arr.length; i++) {
            if(!json[arr[i][id]]){
                res.push(arr[i]);
                json[arr[i][id]] = 1;
            }
        }
        return res;
    };

    //生成唯一id
    Tools.createUniqueId = function(prefix) {
        return (prefix || '') + new Date().getTime().toString(36) + Math.random().toString(36).slice(2);
    }

    //表格获取数据(获取表头或表体)
    Tools.getTableData =  function(tableid, type){  
      
        var tablehead = $('#'+tableid).next().find('.layui-table-header thead tr th');
            tablebody =  $('#'+tableid).next().find('.layui-table-body tbody tr');
            header = [],
            body = [];
        if(type == 'thead'){
            $.each(tablehead, function(index, item){
                if(!item.getAttribute('class')){
                    var fieldenglish = item.getAttribute('data-field');
                    var fieldname = item.querySelector('div span').innerText;
                    var eachTit = {fieldenglish: fieldenglish, fieldname: fieldname};
                    header.push(eachTit);
                }
            })
            return header
        }else{
            $.each(tablebody, function(i, eachTr){ //只需要验证勾选的列
                var allTd = eachTr.querySelectorAll('td'), obj = {};
                $.each(allTd, function(i2, eachTd){
                    if(!!$(this).attr('lay-event')){
                        eachTd.removeAttribute('style');
                        var tdFill = eachTd.getAttribute('lay-event') ? eachTd.getAttribute('lay-event').split(',') : '',
                            fieldenglish = eachTd.getAttribute('data-field');
                        if(!!tdFill[1] != 'varchar'){ 
                            var eachTdVal = eachTd.innerText;
                            if(tdFill[0] == '1' && $.trim(eachTdVal) == ''){ //验证必填
                                eachTd.setAttribute('style', 'background-color: pink;');
                                layer.msg('该列为必填项，请仔细填写！');
                                return ;
                            }
                            obj[fieldenglish] = eachTdVal;
                        }else{ //日期格式
                            var eachInputVal = eachTd.querySelector('input').value;
                            if(tdFill[0] == '1' && $.trim(eachInputVal) == ''){ //验证必填
                                eachTd.setAttribute('style', 'background-color: pink;');
                                layer.msg('该列为必填项，请仔细填写！');
                                return ;
                            }
                            obj[fieldenglish] = eachInputVal;
                        }
                    }
                })
                body.push(obj);
            })
            return body
        }
    };

    //表格获取数据(获取表头或表体)
    Tools.getSerachData =  function(tableid, type){ 
        var tablehead = $('#'+tableid).next().find('.layui-table-header thead tr th');
            tablebody =  $('#'+tableid).next().find('.layui-table-body tbody tr');
            header = [],
            body = [];  
        if(type == 'thead'){
            $.each(tablehead, function(index, item){
                if(!item.getAttribute('class')){
                    var fieldenglish = item.getAttribute('data-field');
                    var fieldname = item.querySelector('div span').innerText;
                    var eachTit = {fieldenglish: fieldenglish, fieldname: fieldname};
                    header.push(eachTit);
                }
            })
            return header;
        }else if(type == 'searchBody'){  
            $.each(tablebody, function(i, eachTr){ 
                var allTd = eachTr.querySelectorAll('td'), obj = {};
                $.each(allTd, function(i2, eachTd){
                    if(!!eachTd.getAttribute('lay-event')){
                        var fieldenglish = eachTd.getAttribute('data-field');
                        obj[fieldenglish] = eachTd.innerText;
                    }
                })
                body.push(obj);
            })
            return body;
        }else if(type == 'searchBodyData'){ //减灾司获取表格数据
            $.each(tablebody, function(i, eachTr){ 
                var allTd = eachTr.querySelectorAll('td'), obj = {}; 
                $.each(allTd, function(i2, eachTd){  
                    if(i2==0){
                       return
                    }else{  
                        var fieldenglish = eachTd.getAttribute('data-field');
                        obj[fieldenglish] = eachTd.innerText;
                    }
                    // if(!eachTd.getAttribute('lay-event')){
                       
                    // }
                })
                body.push(obj);
            })
            return body;
        }else if(type == 'searchBodyData2'){ //减灾司获取表格数据
            $.each(tablebody, function(i, eachTr){ 
                var allTd = eachTr.querySelectorAll('td'), obj = {}; 
                $.each(allTd, function(i2, eachTd){  
                    if(i2==allTd.length-1){
                       return
                    }else{   
                        var fieldenglish = eachTd.getAttribute('data-field');
                        obj[fieldenglish] = eachTd.innerText;
                    }
                    // if(!eachTd.getAttribute('lay-event')){
                       
                    // }
                })
                body.push(obj);
            })
            return body;
        }else if(type == 'body'){ //指标数据任务创建
            $.each(tablebody, function(i, eachTr){ 
                var allTd = eachTr.querySelectorAll('td'), obj = {};
                $.each(allTd, function(i2, eachTd){
                    if(!!eachTd.getAttribute('lay-event')){
                        var tdFill = eachTd.getAttribute('lay-event') ? eachTd.getAttribute('lay-event').split(',') : '',
                            fieldenglish = eachTd.getAttribute('data-field');
                        
                        if(tdFill[1] == 'varchar' || tdFill[1] == 'integer'||tdFill[1]=='decimal' ){ 
                            var eachTdVal = eachTd.innerText;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachTdVal : '';
                        }else if(tdFill[1] == 'date'){  
                            var eachInputVal = eachTd.querySelector('div').innerText;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachInputVal : '';
                        } else if(tdFill[1]=='select'){ 
                            var eachSeletVal = eachTd.querySelector('select').value;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachSeletVal : '';
                        } 
                    }
                })
                body.push(obj);
            }) 
            return body ;
        }
        else {
            $.each(tablebody, function(i, eachTr){ 
                var allTd = eachTr.querySelectorAll('td'), obj = {};
                $.each(allTd, function(i2, eachTd){
                    if(!!eachTd.getAttribute('lay-event')){
                        var tdFill = eachTd.getAttribute('lay-event') ? eachTd.getAttribute('lay-event').split(',') : '',
                            fieldenglish = eachTd.getAttribute('data-field');
                        
                        if(tdFill[1] == 'varchar' || tdFill[1] == 'integer'||tdFill[1]=='decimal' ){ 
                            var eachTdVal = eachTd.innerText;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachTdVal : '';
                        }else if(tdFill[1] == 'date'){ 
                            var eachInputVal = eachTd.querySelector('input').value;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachInputVal : '';
                        } else if(tdFill[1]=='select'){ 
                            var eachSeletVal = eachTd.querySelector('select').value;
                            fieldenglish != 'statename' ? obj[fieldenglish] = eachSeletVal : '';
                        } 
                    }
                })
                body.push(obj);
            })
            return body ;
        }
    };
    /**
     * 两对象比较，反回一个新的对象
     * stateObj,AlldataObj
     */ 
    //兼容ie8
    Object.prototype.hasOwnProperty.call(window, "property")
    Tools.getComposeObj=function (stateObj,allDataObj) { 
            for(var key in allDataObj){  
                if(stateObj.hasOwnProperty(key)){
                    stateObj[key]=allDataObj[key]
                }
            }
            return stateObj;

    }
    //获取选中的行数据
    /**
     * tableid: 表格id
     * row: 获取表格行的状态
     */
    Tools.getTableRow = function(tableid, formdata, row,changeFlag){    
        var tablebody =  $('#'+tableid).next().find('.layui-table-body tbody tr'),
            formField = formdata.form_field;
            body = [];  
        if(row == 'checked'){
            $.each(tablebody, function(i, eachTr){  
                var myTd = [], allTd = eachTr.querySelectorAll('td');
                $.each(allTd, function(kndex, ktem){  
                    if(!!$(this).attr('lay-event') && $(this).attr('data-field') !== 'statename'){
                        myTd.push(ktem);
                    }
                });
                var checkTd = allTd[2].querySelector('.layui-form-checkbox');
                 var   isCheck = checkTd.className.indexOf('layui-form-checked');
                if(isCheck !== -1){
                    var obj = {};
                    $.each(myTd, function(eachIndex, eachTd){
                        eachTd.removeAttribute('style');
                        var tdFill = eachTd.getAttribute('lay-event').split(','),
                            fieldenglish = formField[eachIndex].fieldenglish;
                        if(tdFill[1] == 'varchar' || tdFill[1] == 'integer'||tdFill[1]=='decimal'||tdFill[1]=='upload'){ 
                            var eachTdVal = eachTd.innerText == '提示' ? '' : eachTd.innerText;
                            if(tdFill[0] == '1' && (tdFill[1] == 'varchar'||tdFill[1] == 'integer'|| tdFill[1]=='decimal') && $.trim(eachTdVal) == ''){
                                eachTd.setAttribute('style', 'background-color: pink;');
                                layer.msg('该列为必填项，请仔细填写！');
                                return ;
                            }
                            obj[fieldenglish] = eachTdVal;
                        }else if(tdFill[1] == 'select'||tdFill[1] == 'pulldown'){
                            var text = $(this).find('option:selected').text(),
                                eachSelVal = text != '请选择数据' ? text : '';
                                if(tdFill[0] == '1' && $.trim(eachSelVal) == ''){
                                    eachTd.setAttribute('style', 'background-color: pink;');
                                    layer.msg('该列为必填项，请仔细填写！');
                                    return ;
                                }
                                obj[fieldenglish] = eachSelVal;
                        }else if(tdFill[1] == 'date'){ 
                            var eachInputVal = eachTd.querySelector('input').value;
                            if(tdFill[0] == '1' && $.trim(eachInputVal) == ''){ //验证必填
                                eachTd.setAttribute('style', 'background-color: pink;');
                                layer.msg('该列为必填项，请仔细填写！');
                                return ;
                            }
                            obj[fieldenglish] = eachInputVal;
                        } 
                    });
                    body.push(obj);
                }
            }) 
        }else if(row == 'isFill'){ 
                $.each(tablebody, function(i, eachTr){ 
                    var allTd = [], flag = false;
                    $.each(eachTr.querySelectorAll('td'), function(kndex, ktem){
                        if(!!$(this).attr('lay-event') && $(this).attr('data-field') !== 'statename'){
                            allTd.push(ktem);
    
                        }
                    }); 
                    $.each(allTd, function(i2, eachTd){
                        eachTd.removeAttribute('style');
                        var tdVal = eachTd.innerText, eachInputVal;
                        if(eachTd.querySelector('input')){ eachInputVal = eachTd.querySelector('input').value; } 
                        if($.trim(tdVal) != '' || $.trim(eachInputVal) != '' && !flag){
                            flag = true; var obj = {};
                            $.each(allTd, function(eachIndex, eachTd){
                                var tdFill = eachTd.getAttribute('lay-event') ? eachTd.getAttribute('lay-event').split(',') : '',
                                    // fieldenglish = eachTd.getAttribute('data-field');
                                    fieldenglish = formField[eachIndex].fieldenglish;
                                if(tdFill[1] == 'varchar'||tdFill[1] == 'integer'||tdFill[1]=='decimal'||tdFill[1]=='upload'){ //varchar不需要验证必填
                                    var eachTdVal = eachTd.innerText == '提示' ? '' : eachTd.innerText;
                                        if((tdFill[1] == 'varchar'||tdFill[1] == 'integer'|| tdFill[1]=='decimal') && tdFill[0] == '1' && $.trim(eachTdVal) == ''){
                                            eachTd.setAttribute('style', 'background-color: pink;');  
                                            layer.msg('该列为必填项，请完整填写');
                                            return ;
                                        }
                                    obj[fieldenglish] = eachTdVal;
                                }else if(tdFill[1] == 'date'){ //日期格式
                                    var eachInputVal = eachTd.querySelector('input').value; 
                                        if(tdFill[0] == '1' && $.trim(eachInputVal) == ''){
                                            eachTd.setAttribute('style', 'background-color: pink;');
                                            layer.msg('该列为必填项，请仔细填写！');
                                            return ;
                                        } 
                                    obj[fieldenglish] = eachInputVal;
                                }else if(tdFill[1] == 'select'||tdFill[1] == 'pulldown'){
                                    var text = $(this).find('option:selected').text();
                                    eachSelVal = text != '请选择数据' ? text : ''; 
                                        if(tdFill[0] == '1' && $.trim(eachSelVal) == ''){
                                            eachTd.setAttribute('style', 'background-color: pink;');
                                            layer.msg('该列为必填项，请仔细填写！');
                                            return ;
                                        } 
                                    
                                    obj[fieldenglish] = eachSelVal;
                                } 
                            });
                            body.push(obj);
                            return false;
                        }
                    });
                }); 
            
            
        }
        console.log('body', body)
        return body
    } 
    Tools.getSaveTableRow = function(tableid, formdata, row,changeFlag){
        var emptyFlag=true; 
            var newTabody=[];
            var tablebody =  $('#'+tableid).next().find('.layui-table-body tbody tr'),
            formField = formdata.form_field; 
            $.each(tablebody, function(i, eachTr){ 
                var allTd2 = [], flag = false;
                $.each(eachTr.querySelectorAll('td'), function(kndex, ktem){
                    if(!!$(this).attr('lay-event') && $(this).attr('data-field') !== 'statename'){
                        allTd2.push(ktem); 
                    }
                }); 
                $.each(allTd2, function(i2, eachTd){
                    eachTd.removeAttribute('style');
                    var tdVal2 = eachTd.innerText, eachInputVal2;
                    if(eachTd.querySelector('input')){ eachInputVal2 = eachTd.querySelector('input').value; } 
                    if($.trim(tdVal2) != '' || $.trim(eachInputVal2) != '' && !flag){
                        flag = true; var obj2 = {};
                        $.each(allTd2, function(eachIndex, eachTd){
                            var tdFill = eachTd.getAttribute('lay-event') ? eachTd.getAttribute('lay-event').split(',') : '',
                                // fieldenglish = eachTd.getAttribute('data-field');
                                fieldenglish2 = formField[eachIndex].fieldenglish; 
                                if(tdFill[1] == 'varchar' || tdFill[1] == 'integer'||tdFill[1]=='decimal'){ //varchar不需要验证必填
                                    var eachTdVal = eachTd.innerText == '提示' ? '' : eachTd.innerText; 
                                    obj2[fieldenglish2] = eachTdVal;
                                }else if(tdFill[1] == 'date'){ //日期格式
                                    var eachInputVal = eachTd.querySelector('input').value;  
                                    obj2[fieldenglish2] = eachInputVal;
                                }else if(tdFill[1] == 'select'){
                                    var text = $(this).find('option:selected').text();
                                    eachSelVal = text != '请选择数据' ? text : '';  
                                    obj2[fieldenglish2] = eachSelVal;
                                }
                                })  
                                newTabody.push(obj2);
                                return false; 
                        }
                    })   
                })    
            
            for(var i=0;i<newTabody.length;i++){ 
                if(!Tools.isEmpty(newTabody[i])){
                    emptyFlag= Tools.isEmpty(newTabody[i]); 
                    return emptyFlag
                } 
            }   
        return emptyFlag;
    }
    Tools.handleAddData = function(Data, valData){
        for(var i = 0; i < valData.length; i++){
            valData[i].id = Data[i].id ? Data[i].id : '';
            valData[i].model = Data[i].model ? Data[i].model : '';
            valData[i].statename = Data[i].statename ? Data[i].statename : '';
            valData[i].dept_name = Data[i].dept_name ? Data[i].dept_name : '';
            valData[i].writeid = Data[i].writeid ? Data[i].writeid : '';
            valData[i].state = Data[i].state ? Data[i].state : '';
            valData[i].dept_id = Data[i].dept_id ? Data[i].dept_id : '';
            valData[i].tableId = Data[i].tableId ? Data[i].tableId : '';
            valData[i].writeuser_com_id = Data[i].writeuser_com_id ? Data[i].writeuser_com_id : '';
        }
        return valData;
    }

    /**
     * startTime:开始时间
     * hour: 要增减的时间(小时)
     * dir: 'add':增加;'reduce':减少,默认增加
     */
    Tools.addTime= function(startTime,hour,dir) {
        var regPos =/^\+?[1-9][0-9]*$/; // 正整数
        
        if(!(startTime instanceof Date)) {
            startTime = new Date(startTime);
        }
        if(!startTime instanceof Date) {
            console.error('请传入可识别的日期对象');
            return false;
        }
        if(!regPos.test(hour)){
            console.error('增减时间需为数字小时');
            return false;
        }
        var start = startTime.getTime(),
            hourTime = hour*60*60*1000,
            endTime = new Date();
        if(!dir || dir === 'add') {
            endTime = new Date(start + hourTime);
        }else if(dir === 'reduce'){
            endTime = new Date(start - hourTime);
        }
        var oYear = endTime.getFullYear(),
        oMonth = endTime.getMonth()+1,
        oDay = endTime.getDate(),
        oHour = endTime.getHours(),
        oMin = endTime.getMinutes(),
        oSen = endTime.getSeconds(),
        oTime = oYear +'-'+ Tools.addZero(oMonth) +'-'+ Tools.addZero(oDay) +' '+ Tools.addZero(oHour) +':'+Tools.addZero(oMin) +':'+Tools.addZero(oSen);
        return oTime;
    }

    /**
     * 两位数补0
     */
    Tools.addZero = function(num){
        if(parseInt(num) < 10){
            num = '0'+num;
        }
        return num;
    }

    /**
     * 获取年月日
     */
    Tools.commenDate = function(time){
        return { year: moment(time).format('YYYY'), month: moment(time).subtract(1, 'months').format('MM'), date: moment(time).format('DD')}
    }

    //设置最小可选的日期
    Tools.minDate = function(type){
        var now = new Date();
        if(type == 'date'){
            return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
        }else if(type == 'datetime'){
            return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + '-' + now.getHours();
        }
    }
    
    /**
     * name layui合并tbody中单元格的方法
     * @param tableId  表格的id属性
     * @param fieldName 要合并的列field值
     * @desc 此方式适用于没有列冻结的单元格合并
     */
    Tools.tableRowSpanNoFixedCol = function(tableId, fieldName){
        if (!tableId && !fieldName) {
            console.log('tableId, fieldName为必填项');
            return false;
        }
        // 获取页面中全部的表格元素
        var allTableNode = document.getElementsByClassName("layui-table-view");

        // 获取lay-id属性为tableId的表格元素的
        var targetTableNode = null;
        if (allTableNode.length > 0) {
            for (var index = 0, length = allTableNode.length; index < length; index++) {
                // 通过lay-id属性过滤表格元素
                var tableLayId = allTableNode[index].getAttribute("lay-id");
                if (tableLayId === tableId) {
                    targetTableNode = allTableNode[index];
                    break;
                }
            }
        }
        if (!targetTableNode) {
            console.log('没有找到ID为：' + tableId + '的表格, 请升级您的layui版本');
            return false;
        }

        // 开始合并单元格操作
        var tBodyNode = targetTableNode.getElementsByClassName("layui-table-body")[0];

        var tdNodes = tBodyNode.getElementsByTagName("td");
        var childFilterArr = [];
        // 获取data-field属性为fieldName的td
        for (var i = 0; i < tdNodes.length; i++) {
            if (tdNodes[i].getAttribute("data-field") === fieldName) {
                childFilterArr.push(tdNodes[i]);
            }
        }

        // 获取td的个数和种类
        var childFilterTextObj = {};
        var childFilterArrLength = childFilterArr.length;
        for (var j = 0; j < childFilterArrLength; j++) {
            var childText = childFilterArr[j].textContent;
            if (childFilterTextObj[childText] === undefined) {
                childFilterTextObj[childText] = 1;
            } else {
                var num = childFilterTextObj[childText];
                childFilterTextObj[childText] = num * 1 + 1;
            }
        }
        // 给获取到的td设置合并单元格属性
        for (var key in childFilterTextObj) {
            var tdNum = childFilterTextObj[key];
            var canRowSpan = true;
            var needChangeBackGroundNodes = [];
            var addEventNode = null;
            for (var h = 0; h < childFilterArrLength; h++) {
                if (childFilterArr[h].textContent === key) {
                    needChangeBackGroundNodes.push(childFilterArr[h]);
                    if (canRowSpan) {
                        childFilterArr[h].setAttribute("rowspan", tdNum);
                        addEventNode = childFilterArr[h];
                        canRowSpan = false;
                    } else {
                        childFilterArr[h].style.display = "none";
                    }
                }
            }

            // 以下为单元格鼠标悬浮样式修改(使用闭包)
            (function (addEventNode, needChangeBackGroundNodes) {
                addEventNode.onmouseover = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodes[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                    }
                };
                addEventNode.onmouseout = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodes[index].parentNode.style.background = "";
                    }
                };
            })(addEventNode, needChangeBackGroundNodes);
        }
    }

    /**
     * name layui合并tbody中单元格的方法
     * @param tableId  表格的id属性
     * @param fieldName 要合并的列field值
     * @param leftOrRight 要合并的列fixed值,'left','right'
     * @desc 此方式适用于列冻结的单元格合并
     */
    Tools.tableRowSpanOfFixedCol = function(tableId, fieldName, leftOrRight){
        if (!tableId && !fieldName) {
            console.log('tableId, fieldName为必填项');
            return false;
        }

        // 获取页面中全部的表格元素
        var allTableNode = document.getElementsByClassName("layui-table-view");

        // 获取lay-id属性为tableId的表格元素的
        var targetTableNode = null;
        if (allTableNode.length > 0) {
            for (var index = 0, length = allTableNode.length; index < length; index++) {
                // 通过lay-id属性过滤表格元素
                var tableLayId = allTableNode[index].getAttribute("lay-id");
                if (tableLayId === tableId) {
                    targetTableNode = allTableNode[index];
                }
            }
        }
        if (!targetTableNode) {
            console.log('没有找到ID为：' + tableId + '的表格,请升级您的layui版本');
            return false;
        }
        // 左侧列为冻结的情况
        var tBodyNode = targetTableNode.getElementsByClassName("layui-table-body")[0];
        var tBodyNodeFixed = null;
        if (leftOrRight === 'right') {
            tBodyNodeFixed = targetTableNode.getElementsByClassName("layui-table-fixed-r")[0];
        } else {
            tBodyNodeFixed = targetTableNode.getElementsByClassName("layui-table-fixed-l")[0];
        }

        var tdNodesFixed = tBodyNodeFixed.getElementsByTagName("td");
        var tdNodes = tBodyNode.getElementsByTagName("td");
        var childFilterArrFixed = [];
        var childFilterArr = [];
        // 获取data-field属性为fieldName的td
        for (var i = 0; i < tdNodesFixed.length; i++) {
            if (tdNodesFixed[i].getAttribute("data-field") === fieldName) {
                childFilterArrFixed.push(tdNodesFixed[i]);
            }
        }
        for (var l = 0; l < tdNodes.length; l++) {
            if (tdNodes[l].getAttribute("data-field") === fieldName) {
                childFilterArr.push(tdNodes[l]);
            }
        }
        // 获取td的个数和种类
        var childFilterArrLength = childFilterArrFixed.length;
        var childFilterTextObj = {};
        for (var j = 0; j < childFilterArrLength; j++) {
            var childText = childFilterArrFixed[j].textContent;
            if (childFilterTextObj[childText] === undefined) {
                childFilterTextObj[childText] = 1;
            } else {
                var num = childFilterTextObj[childText];
                childFilterTextObj[childText] = num * 1 + 1;
            }
        }
        // 给获取到的td设置合并单元格属性
        for (var key in childFilterTextObj) {
            var tdNum = childFilterTextObj[key];
            var canRowSpan = true;
            var needChangeBackGroundNodesFixed = [];
            var needChangeBackGroundNodes = [];
            var addEventNode = null;
            for (var h = 0; h < childFilterArrLength; h++) {
                if (childFilterArrFixed[h].innerText === key) {
                    needChangeBackGroundNodesFixed.push(childFilterArrFixed[h]);
                    if (canRowSpan) {
                        childFilterArrFixed[h].setAttribute("rowspan", tdNum);
                        addEventNode = childFilterArrFixed[h];
                        canRowSpan = false;
                    } else {
                        childFilterArrFixed[h].style.display = "none";
                    }
                }
            }
            for (var m = 0; m < childFilterArrLength; m++) {
                if (childFilterArr[m].innerText === key) {
                    needChangeBackGroundNodes.push(childFilterArr[m]);
                }
            }

            // 以下为单元格鼠标悬浮样式修改(使用闭包)
            (function (addEventNode, needChangeBackGroundNodes, needChangeBackGroundNodesFixed) {
                addEventNode.onmouseover = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodesFixed[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                        needChangeBackGroundNodes[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                    }
                };
                addEventNode.onmouseout = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodesFixed[index].parentNode.style.background = "";
                        needChangeBackGroundNodes[index].parentNode.style.background = "";
                    }
                };
            })(addEventNode, needChangeBackGroundNodes, needChangeBackGroundNodesFixed);
        }
    }

    //加载表格下拉框
    Tools.loadSelectFunction = function(supContent){  
        for(var key in supContent){
            var vals = supContent[key],
                tableId = vals[0].tableId,
                allTds = $('#'+tableId+' td[data-field='+key+']');
            layui.each(allTds, function(index, item){
                var div = $(this).find('div'),
                    field = $(this).attr('data-field'),
                    html = '<select class="'+field+' formSelectBox" lay-ignore><option value="">请选择数据</option>';
                layui.each(vals, function(i, content){
                    if(content.checked){
                        html += '<option value="'+content.text+'" selected="true">'+content.text+'</option>'
                    }else{
                        html += '<option value="'+content.text+'">'+content.text+'</option>'
                    }
                })
                html += '</select>';
                div.html(html);
                $(this).removeAttr('data-edit');
                var event = $(this).attr('lay-event') ? $(this).attr('lay-event') .split(',') : '';
                $(this).attr('lay-event', event[0]+',select');
            })
        }
    }

    //对外暴露的接口
    Tools.handleSelectVal = function(supContent, data, id){
        for(var key in supContent){
            layui.each(supContent[key], function(j, content){
                content.tableId = id;
            })
        }
        return supContent;
    }

    //设置全局字体大小
    Tools.setFont = function(layout, size, iframeId){
        var iframeId = iframeId || '',
            size = size ? size : (layui.sessionData('fontSize').size ? layui.sessionData('fontSize').size : 16),
            font = 'font-size:'+size+'px;';
        if(layout && layout.length > 0){
            layui.each(layout, function(index, item){
                if(iframeId){
                    $('#'+iframeId).contents().find(item).attr('style', font);
                }else{
                    $(item).attr('style', font);
                }
            })
        }
    }

    Tools.initCite = function(router, kqParam, czParam){
        var search = router.search, firstMenu = '', secondMenu = '';
        firstMenu = search.kq && search.kq == '1' ? kqParam.kqfirstMenu : czParam.czfirstMenu;
        secondMenu = search.kq && search.kq == '1' ? kqParam.kqsecondMenu : czParam.czsecondMenu;
        $('.first-breadcrumb').html(firstMenu);
        $('.second-breadcrumb').html(secondMenu);
    }

    Tools.setNavText = function(){
        $('.layui-title-mid').hasClass('layui-hide') ? $('.layui-title-mid').removeClass('layui-hide') : '';
        !$('.custom-card-header').hasClass('card-header-bold') && $('.custom-card-header').addClass('card-header-bold');
    }

    //设置填报表单表头
    Tools.setTaskFormTitle = function(taskname){
        $('.third-breadcrumb').html(taskname);
        $('.card-header-subtitle').html(taskname);
    }

    //去除id相同的用户
    Tools.removeSamePerson = function(arr){
        for(var i=0; i<arr.length; i++){
            var item = arr[i]
            for(var j = i+1; j<arr.length; j++){
                if(item.dataid == arr[j].dataid){
                    arr.splice(j,1)
                    i--;
                }                          
            }
        };
        return arr;
    }

    /*处理出错的数据*/ 
    Tools.handleWarnInfo = function(cols, result){   
        var metaCol = cols[cols.length - 1];
        layui.each(metaCol, function(index, item){
            if(item.field){
                for(var key in result){
                    for(var i in result[key]){
                        if(item.field == i){
                            item[key] = result[key][i];
                            if(item.templet && item.templet == '#datetime'){
                                item.style = 'background-color:#FFB800';
                            }else{
                                item.templet = function(d){
                                    var tips = item[d.id] ? 'lay-tips='+item[d.id]+'' : '',
                                        style = item[d.id] ? 'background-color:#FFB800;height:28px;color:#FFF;' : '',
                                        // text = d[item.field] ? d[item.field] : '<span style="color:#FF5722;">提示</span>';
                                        text = d[item.field] ? d[item.field] : '<span style="color:#FF5722;">提示</span>';
                                    return '<div style='+style+'><span '+tips+'>'+text+'</span></div>'
                                }
                            }
                        }
                    }
                }
            }
        })
   }

   //计算字符串长度
    Tools.GetStrLength = function(str) {
        var realLength = 0, len = str.length, charCode = -1;
        for (var i = 0; i < len; i++) {
            charCode = str.charCodeAt(i);
            charCode >= 0 && charCode <= 128 ? realLength += 1 : realLength += 2;
        }
        return realLength;
    };

    //处理复杂表格表头
    Tools.handleCols = function(cols, fieldCols){  
        layui.each(cols, function(index, col){
            layui.each(col, function(tndex, item){
                for(var i = 0; i < fieldCols.length; i++){
                    if(item.field && item.field == fieldCols[i].field){
                        item.event = fieldCols[i].event;
                        !!fieldCols[i].edit ? item.edit = fieldCols[i].edit : '';
                        !!fieldCols[i].templet ? item.templet = fieldCols[i].templet : '';
                    }
                }
            });
        });
        return cols;
    }

    //表格新增序号、操作列
    Tools.addOtherCols = function(colsss){  
        for(var i = 0; i < colsss.length; i++){
            layui.each(colsss[i], function(index, item){
                item.colspan == '1' && delete this.colspan;
                item.rowspan == '1' && delete this.rowspan;
                item.align = 'center';
                item.field != 'statename' && item.type != 'numbers' && item.type != 'checkbox' ? item.minWidth = 230 : '';
                if(!item.field){
                    if(item.colspan && item.type != 'checkbox' && !item.toolbar && item.type != 'numbers' && item.colspan == '1'){ //处理单列合并时内容列比表头多出来异常列的情况
                        item.colGroup = true;
                    }
                }
            });
        }	
    }

    //获取表格默认空行数据
    Tools.getGridData = function(cols){
        var val = { statename: '' };
        for(var i = 0; i < cols.length; i++){
            layui.each(cols[i], function(index, col){
                !!col.field ? val[col.field] = '' : '';
            });
        }
        return [val]
    }

    //查找两个数组key不同的元素
    Tools.diffent = function(fArr,cArr,field){
        var diffRes = [];
        var fDatas = [];
        var cDatas = [];
        for(var i in fArr){
            var flg = false
            for(var j in cArr){
                if(cArr[j][field]===fArr[i][field]){
                    flg = true
                    break
                }
            }
            if(!flg){
                fDatas.push(fArr[i])
            }
        }
        for(var i in cArr){
            var flg = false
            for(var j in fArr){
                if(fArr[j][field]===cArr[i][field]){
                    flg = true
                    break
                }
            }
            if(!flg){
                cDatas.push(cArr[i])
            }
        }
        diffRes.push(cDatas.concat(fDatas));
        return diffRes
    }

    /** @method 定位到任务
     * @param taskList 任务列表
     * @param router 路由对象
     * @param tableId 表格id
     */
    Tools.clickToTask =  function(taskList, router, tableId){
        var taskid = router.search.taskid; 
        if(!!taskid){
            layui.each(taskList, function(index, task){
                task.taskid === taskid && $('[lay-id="'+tableId+'"] .layui-table-body tr').eq(index).trigger('click');
            });
        }
    }

    /**
     * @method 全局设置appid
     * @param id 设置的appid
     */
    Tools.setApp = function(admin, id){
        admin.req({
            type:"post",
            url: 'myapi/DC/api/rest/web/custom/setApp',
            data: { app_id: id },
            done: function(res){
                if(res.retcode == '0'){
                    layui.data('userdata', {
                        key: 'appId',
                        value: id
                    });
                    location.hash = '/';
                    location.reload();
                }
            }
        });
    }

    //截取文件路径
    Tools.subUrl = function(url){
        var startIndex = url.indexOf('FileStorage') > 0 ? url.indexOf('FileStorage') : 0;
        return url.substring(startIndex)
    }
    
    /*表头过长显示提示 */
    Tools.showTextTips = function(className){
        $(className).delegate('th .layui-table-cell', 'mouseover', function(){
            var text = $(this).find('span').text(),
                cellClientWidth = $(this).width(),
                spanClientWidth = $(this).find('span').width();
            var index = spanClientWidth >= cellClientWidth ? layer.tips(text, this, { tips: 1 }) : ''
        });  
        $(className).delegate('th .layui-table-cell', 'mouseleave', function(){
            layer.closeAll('tips');
        });  
    }

    //文件上传(无刷新上传)
    Tools.submitUpload = function(element, uploadUrl, callback) {
        //获得文件列表，注意这里不是数组，而是对象
        var fileList = element.files;
        if(!fileList.length){
            return;
        }
        var fd = new FormData();   //构造FormData对象

        //多文件上传需要遍历添加到 fromdata 对象
        for(var i =0;i<fileList.length;i++){
            fd.append('file', fileList[i]);//支持多文件上传
        }

        var xhr = new XMLHttpRequest();   //创建对象
        var url = uploadUrl+'?access_token='+layui.data('layuiAdmin').access_token;
        xhr.open('POST', url, true);

        xhr.send(fd);//发送时  Content-Type默认就是: multipart/form-data; 
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                var res = JSON.parse(xhr.responseText);   //返回值
                res.retcode == 0 ? callback(res) : layer.msg('提示: '+ res.retmsg,{time: 1000});
            }
        }
    }
    //浏览器是否是ie  
    Tools.isIE=function(){ 
         if (!!window.ActiveXObject || "ActiveXObject" in window)  
            { return true; }  
            else  
            { return false; }   
    } 

     
    //dropzone插件文件上传
    Tools.DropzoneUpload = function(el, url, params, callback){    
        if(Tools.isIE()){
            layui.use('upload', function(){
                var upload = layui.upload; 
                upload.render({
                elem: el //绑定元素
                ,url: url+"?access_token="+layui.data('layuiAdmin').access_token//上传接口
                ,accept:'file'
                ,data:params||{}
                ,done: function(res){  
                    callback&&callback(res) 
                }
                ,error: function(index, upload){
                    console.log(upload,"上传失败") 
                  }
                ,error: function(){ 
                    layer.msg('上传文件过大，请重新选择文件上传', {time: 1000});
                }
            });
            });
        }else{ 
            var myDropzone = new Dropzone(el, { 
                url: url+"?access_token="+layui.data('layuiAdmin').access_token,
                method: 'post',
                params: params,
                maxFilesize: 100, //MB
                previewsContainer: document.querySelector('.previewsContainer'),
                accept: function(file, done){ done(); }
            });
            myDropzone.on('complete', function(file){
                if(file.xhr.status === 200){
                    var res = JSON.parse(file.xhr.response);
                    res.retcode === 0 ? callback && callback(res) : layer.msg('提示: '+ res.retmsg,{time: 1000});
                }
            });
        } 
    } 
    //兼容ielayui.uplaod文件上传
    // Tools.upLoadieFun=function(id,uploadFileUrl,callback){
    //     layui.use('upload', function(){
    //         var upload = layui.upload; 
    //         upload.render({
    //         elem: id //绑定元素
    //         ,url: uploadFileUrl+"?access_token="+layui.data('layuiAdmin').access_token//上传接口
    //         ,accept:'file' 
    //         ,done: function(res){ 
    //             callback&&callback(res) 
    //         }
    //         ,error: function(){ 
    //             layer.msg('上传文件过大，请重新选择文件上传', {time: 1000});
    //         }
    //     });
    //     });
    // }
   

    //jquery.form.js文件上传
    Tools.ajaxSubmitFile = function(uploadUrl, form, params, callback){
        var params = params ? params : {};
        var options = {  
            url: uploadUrl+"?access_token="+layui.data('layuiAdmin').access_token, //上传文件的路径  
            type: 'post',
            dataType: 'text',
            data: params,
            success: function(data){  
                callback && callback(data);
            }
        };  
        form.ajaxSubmit(options); 
    } 
    //数据填报处的文件上传
    Tools.DataFillFileUpload = function(el, url, params, callback){
        layui.use('upload', function(){
            var upload = layui.upload; 
                upload.render({
                elem: el //绑定元素
                ,url: url+"?access_token="+layui.data('layuiAdmin').access_token//上传接口
                ,accept:'file'
                ,data:params||{}
                ,done: function(res){ 
                    callback&&callback(res) 
                }
                ,error: function(){ 
                    layer.msg('上传文件过大，请重新选择文件上传', {time: 1000});
                }
            });
        })
    }
    
    exports('tools', Tools);
  });